from odoo import fields, models, api
from odoo.exceptions import UserError, AccessError

VALUE_TYPE = [('courier', '承运商'), ('shipper', '托运商'), ('both', '通用'), ('neither', '都不')]
VALUE_CATEGORY = [('one', '一类'), ('two', '二类')]


class RPValueAddedService(models.Model):
    _name = "rp.value.added.service"
    _description = '增值服务'
    _sql_constraints = [('unique_name', 'UNIQUE(name)', '名称必须唯一')]

    name = fields.Char(string='名称', required=True, copy=False, index=True)
    type = fields.Selection(string='类型', selection=VALUE_TYPE, default=VALUE_TYPE[2][0], required=True)

    category = fields.Selection(string='大类', selection=VALUE_CATEGORY, default=VALUE_CATEGORY[1][0], help='一级是头尾程，二级是标准增值服务')

    color = fields.Integer(string='标签颜色', compute='_depends_get_color', store=True)
    photo = fields.Binary(string='图片', copy=False)
    active = fields.Boolean(string='有效', default=True)

    @api.depends('category')
    def _depends_get_color(self):
        for s in self:
            if s.category == VALUE_CATEGORY[0][0]:
                s.color = 8
            elif s.category == VALUE_CATEGORY[1][0]:
                s.color = 0

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            category = vals.get('level', False)
            if category == VALUE_CATEGORY[0][0]:
                raise AccessError('一类增值服务不允许手动创建')
        return super(RPValueAddedService, self).create(vals_list)

    def write(self, vals):
        if self.category == VALUE_CATEGORY[0][0]:
            raise AccessError("不允许修改一类记录")
        return super(RPValueAddedService, self).write(vals)

    def unlink(self):
        if self.category == VALUE_CATEGORY[0][0]:
            raise AccessError("不允许删除一类记录")
        return super(RPValueAddedService, self).unlink()
